import React, { memo, Fragment, useState, useEffect, useCallback } from "react";
import { withRouter } from "react-router-dom";
import { message } from "antd";
import Qs from "qs";

import { custom } from "services/common";

import HYFormCom from "components/form/index";

const HYJobAdd = memo(function (props: any) {
  const formItem = [
    {
      type: "Input",
      label: "职位名称",
      name: "jobName",
      required: true,
      style: { width: "200px" },
      placeholder: "请输入部门名称",
    },
    {
      type: "SelectComponent",
      label: "部门",
      name: "parentId",
      required: true,
      style: { width: 200 },
      url: "/department/listAll/",
      propsKey: { label: "name", value: "id" },
    },
    {
      type: "Radio",
      label: "禁启用",
      name: "status",
      required: true,
      options: [
        { label: "禁用", value: false },
        { label: "启用", value: true },
      ],
    },
    {
      type: "TextArea",
      label: "描述",
      name: "content",
      required: true,
      style: { width: 400 },
      placeholder: "请输入描述内容",
    },
  ];
  const formLayout = {
    labelCol: { span: 2 },
    wrapperCol: { span: 22 },
  };
  const initialValues = {
    status: false,
    number: 0,
  };
  // 状态
  const [isEdit, setIsEdit] = useState(false);
  const [id, setId] = useState<string>();
  const [editData, setEditData] = useState({});
  // 生命周期
  const handleParams = useCallback(async () => {
    const search = props.location.search;
    if (search) {
      const id = Qs.parse(search)["?id"];
      const ids = id as string;
      if (!!ids) {
        setIsEdit(true);
        setId(ids);
        edit(ids);
      }
    }
  }, [props.location.search]);
  useEffect(() => {
    handleParams();
  }, [handleParams]);

  const edit = async (id: string) => {
    const res: any = await custom({ url: "/job/detailed/", data: { id: +id } });
    setEditData({ ...res.data });
  };
  //
  const onFinish = async (params: any, form: any) => {
    try {
      //  添加 修改
      if (id) {
        params.jobId = +id;
        const res: any = await custom({ url: "/job/edit/", data: params });
        message.success(res.message);
      } else {
        const res: any = await custom({ url: "/job/add/", data: params });
        message.success(res.message);
      }
      form.resetFields();
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <Fragment>
      <HYFormCom
        formItem={formItem}
        formLayout={formLayout}
        submit={onFinish}
        editData={editData}
        initialValues={initialValues}
        isEdit={isEdit}
      />
    </Fragment>
  );
});

export default withRouter(HYJobAdd);
